package fi.pakkanen.yarpg.core;

import fi.pakkanen.yarpg.tools.Range;

/**
 * A game map.
 * 
 * @author Oliver Michels <oliver.michels@gmx.net>
 * 
 */
public class GameMap {

	/** The name of the map */
	private final String name;

	/** The range of valid positions on the x-axis */
	private final Range xExtent;

	/** The range of valid positions on the y-axis */
	private final Range yExtent;

	private final int hashCode;

	/**
	 * Create a new game map.
	 * 
	 * @param name
	 * @param xExtent
	 * @param yExtent
	 */
	public GameMap(String name, int xExtent, int yExtent) {
		this.name = name;
		this.xExtent = new Range(0, xExtent);
		this.yExtent = new Range(0, yExtent);
		this.hashCode = calculateHashCode();
	}

	/**
	 * Get the name of the map
	 * 
	 * @return the name
	 */
	public String getName() {
		return name;
	}

	/**
	 * Check whether a given position is valid.
	 * 
	 * @param position
	 * @return true when the given position is valid, false otherwise
	 */
	public boolean isPositionValid(Position position) {
		return xExtent.isInRange(position.getX()) && yExtent.isInRange(position.getY());
	}

	/**
	 * Calculate the hash code of this range.
	 * 
	 * @return the hash code
	 */
	private int calculateHashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + ((xExtent == null) ? 0 : xExtent.hashCode());
		result = prime * result + ((yExtent == null) ? 0 : yExtent.hashCode());
		return result;
	}

	@Override
	public String toString() {
		return "GameMap[" + name + "]";
	}

	@Override
	public int hashCode() {
		return hashCode;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj) {
			return true;
		}
		if (obj == null) {
			return false;
		}
		if (getClass() != obj.getClass()) {
			return false;
		}
		GameMap other = (GameMap) obj;
		if (name == null) {
			if (other.name != null) {
				return false;
			}
		} else if (!name.equals(other.name)) {
			return false;
		}
		if (xExtent == null) {
			if (other.xExtent != null) {
				return false;
			}
		} else if (!xExtent.equals(other.xExtent)) {
			return false;
		}
		if (yExtent == null) {
			if (other.yExtent != null) {
				return false;
			}
		} else if (!yExtent.equals(other.yExtent)) {
			return false;
		}
		return true;
	}
}
